<?php
/**
 * 文件上传类
 * @param
 * @author Mr.Liu
 * @Time: 15:16
 */

namespace App\Services;
use Illuminate\Http\Exceptions\PostTooLargeException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadService
{
    protected $request;
    protected $diskDir;
    protected $uploadField;
    protected $disk;

    const  SuccessStatus = 1;
    const  FailStatus = 0;

    public function __construct(Request $request,$diskDir = 'files',$uploadField = 'file',$disk='uploads')
    {
        $this->request = $request;
        $this->diskDir = $diskDir;
        $this->disk = $disk;
        $this->uploadField = $uploadField;
    }


    public function upload(){
        try {
            if ($this->request->hasFile($this->uploadField)) {

                $path = $this->request->file($this->uploadField)->store($this->diskDir, $this->disk);

                $response = [
                    'message' => "上传成功",
                    'status' => self::SuccessStatus,
                    'url' => Storage::disk($this->disk)->url($path),
                    'path' => $path
                ];

            } else {
                throw new \Exception('参数异常');
            }
        }catch (PostTooLargeException $exception){

            $response = [
                'message'   =>  '文件太大',
                'status'    =>  self::FailStatus
            ];

        }catch (\Exception $exception){

            $response = [
                'message'   =>  $exception->getMessage(),
                'status'    =>  self::FailStatus
            ];

        }
        return $response;
    }
}